<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton,
  ElMessageBox,
  ElMessage,
  ElInput,
  ElDialog,
  ElPopover,
  ElSelect,
  ElOption
} from 'element-plus'
import {
  sendIndex,
  sendDel,
  sendEdit,
  deliverSetStatus,
  deliverCombine,
  storeSelect,
  deliverExport,
  fhdExportExcel
} from '@/api/common'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive, onActivated, h } from 'vue'
import Write from './components/Write.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useRouter } from 'vue-router'
import { useEmitt } from '@/hooks/web/useEmitt'
import { Dialog } from '@/components/Dialog'
import Detail from './components/Detail.vue'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'

const { t } = useI18n()

defineOptions({
  name: 'Invoice'
})

const appStore = useAppStoreWithOut()
const { wsCache } = useCache()
//用户权限数组
const userRlues = wsCache.get(appStore.getUserInfo).rlues
const userId = wsCache.get(appStore.getUserInfo).id

const checkRlues = (rlues) => {
  //检查权限
  if (userRlues.includes(rlues)) {
    return true
  } else {
    ElMessage.error('当前用户无权限操作，请联系管理员')
    return false
  }
}
const { push } = useRouter()
const { register, tableObject, methods } = useTable<any>({
  getListApi: sendIndex,
  delListApi: sendDel,
  response: {
    list: 'data',
    total: 'total'
  },
  defaultParams: {
    filter: '{"status":"0"}',
    op: '{"status":"="}'
  },
  find: userRlues.includes('201') ? -1 : userId
})

const { getList, setSearchParams } = methods

// onActivated(() => {
//   let needFrefresh = localStorage.getItem('needRefresh')
//   if (needFrefresh) {
//     getList()
//     localStorage.removeItem('needRefresh')
//   }
// })

const { emitter } = useEmitt()

getList()

useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      tableObject.currentPage = 1
    }
    getList()
  }
})

const ydString = ref('')
const tkShow = ref(false)
const store_id = ref()
const confirmTk = async () => {
  if (ydString.value) {
    ydString.value = ydString.value.replace(/，/g, ',')
  }

  const res = await deliverCombine({
    deliver_ids: ydString.value,
    store_id: store_id.value,
    comment: ''
  })
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'delivery_date',
    width: '150px',
    label: t('invoice.receivingDate'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'send_time',
    width: '150px',
    label: t('invoice.deliveryTime'),
    search: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'placestart_text',
    width: '140px',
    label: t('router.origin'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'placeend_text',
    width: '140px',
    label: t('router.destination'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'client_code',
    width: '70px',
    label: t('customerManagement.customerNo'),
    search: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'shouhuo',
    width: '80px',
    label: t('customerManagement.consignee'),
    search: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'remark',
    width: '120px',
    label: t('userDemo.remark'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'transport_text',
    width: '150px',
    label: t('router.transport'),
    formatter: (row: any) => {
      return h(
        'span',
        row.transport_text
          ? row.transport_text.replace(/[0-9]/g, '')
          : row.transport_text.replace(/[0-9]/g, '')
      )
    },
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'waybill',
    label: t('invoice.waybillNumber'),
    search: {
      show: true
    },
    width: 150,
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'units',
    width: '80px',
    label: '件数',
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'weight',
    width: '80px',
    label: '重量',
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'density',
    width: '80px',
    label: '密度',
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'volume',
    width: '80px',
    label: '体积',
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'remark',
    width: '120px',
    label: t('invoice.productNameRemarks'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },

  {
    field: 'quantity',
    width: '90px',
    label: t('invoice.packingQuantity'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'usd_value',
    width: '80px',
    label: t('invoice.usDollarCreditValue'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'pack_fee',
    width: '80px',
    label: t('invoice.packingCharges'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'short_fee_cny',
    width: '80px',
    label: t('invoice.shortdistancefee'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'imitate_text',
    width: '80px',
    label: t('invoice.whetherToImitateTheBrand'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'delivery_market',
    width: '80px',
    label: '到货市场',
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'status',
    width: '120px',

    label: t('invoice.documentStatus'),
    table: {
      show: false
    },
    search: {
      show: false,
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '仓库保存',
            value: 0
          },
          {
            label: '仓库提交',
            value: '1'
          },
          {
            label: '制单保存',
            value: '2'
          },
          {
            label: '制单提交',
            value: '3'
          },
          {
            label: '已审核',
            value: '4'
          },
          {
            label: '已到货',
            value: '5'
          }
        ]
      }
    },
    form: {
      show: false
    },
    detail: {
      span: 24,
      show: false
    }
  },
  {
    field: 'status_text',
    label: t('invoice.documentStatus'),
    search: {
      show: false
    },
    form: {
      show: false
    },
    detail: {
      span: 24,
      show: false
    }
  },
  {
    field: 'send_time',
    label: t('common.TimeText'),
    table: {
      show: false
    },
    search: {
      show: false,
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD'
      }
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 6,
      show: true
    }
  },
  {
    field: 'fahuo',
    width: '80px',
    label: t('customerManagement.shipper'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'weight',
    width: '90px',
    label: t('invoice.totalWeight'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'volume',
    width: '90px',
    label: t('invoice.totalVolume'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'units',
    width: '90px',
    label: t('invoice.totalNumberOfpices'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'shouhuo_mobile',
    width: '140px',
    label: t('customerManagement.consigneePhone'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'submarket_text',
    width: '120px',
    label: t('router.distributionMarket'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'store_text',
    width: '100px',
    search: {
      show: true
    },
    label: t('invoice.locationOfGoods'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'insurance_rate',
    width: '80px',
    label: t('invoice.guaranteeRate'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'base_freight',
    width: '80px',
    label: t('invoice.businessFloorFreight'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'other_fund',
    width: '80px',
    label: t('invoice.otherReceivables'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'agency_fund',
    width: '80px',
    label: t('invoice.invoicing'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'transport_price',
    width: '80px',
    label: t('invoice.fieghtPrice'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'total_fee',
    width: '80px',
    label: t('invoice.totalReceivableExpenses'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'paytype_text',
    width: '120px',
    label: t('invoice.paymentMethod'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'explain',
    width: '120px',
    label: t('invoice.illustrate'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'insurance_fee',
    width: '80px',
    label: t('invoice.insurancePremiumsReceivabl'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'action',
    width: '60px',
    label: t('formDemo.operate'),
    form: {
      show: false
    },
    fixed: 'right',
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const AddAction = (rlues) => {
  if (checkRlues(rlues)) push('/logistics/invoiceAdd')
}
const cos = async () => {
  console.log('????')
  tkShow.value = true

  // ElMessageBox.confirm(`是否合包?`, t('common.delWarning'), {
  //   confirmButtonText: t('common.delOk'),
  //   cancelButtonText: t('common.delCancel'),
  //   type: 'warning'
  // }).then(async () => {
  //   const res = await deliverCombine({
  //     deliver_ids: deliver_ids,
  //     store_id: store_id,
  //     comment: ''
  //   })
  //   if (res) {
  //     ElMessage.success('合包成功')
  //     emitter.emit('getList', 'edit')
  //   }
  // })
}

const delLoading = ref(false)

const delData = async (row: TableData | null, multiple: boolean, ruls: string) => {
  if (!checkRlues(ruls)) return false
  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? selections.map((v) => v.id) : [tableObject.currentRow?.id as string],
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}

// const actionType = ref('')
const dialogTitle = ref('')
const dialogVisible = ref(false)
const action = async (row: TableData, type: string, ruls: string) => {
  if (!checkRlues(ruls)) return false
  switch (type) {
    case 'Edit':
      {
        push(`/logistics/invoice${type}?id=${row.id}&isEdit=true`)
      }
      break
    case 'Passed':
      {
        ElMessageBox.confirm(`是否${t('purchaseOrder.passedReview')}?`, t('common.delWarning'), {
          confirmButtonText: t('common.delOk'),
          cancelButtonText: t('common.delCancel'),
          type: 'warning'
        }).then(async () => {
          const res = await deliverSetStatus({
            ids: row.id,
            status: 4
          })
          if (res) {
            ElMessage.success('提交成功')
            emitter.emit('getList', 'edit')
          }
        })
      }
      break
    case 'ckSubmit':
      {
        // ElMessageBox.confirm(`是否提交仓库?`, t('common.delWarning'), {
        ElMessageBox.confirm(`是否提交配货?`, t('common.delWarning'), {
          confirmButtonText: t('common.delOk'),
          cancelButtonText: t('common.delCancel'),
          type: 'warning'
        }).then(async () => {
          const res = await deliverSetStatus({
            ids: row.id,
            status: 6
          })
          if (res) {
            ElMessage.success('提交成功')
            emitter.emit('getList', 'edit')
          }
        })
      }
      break
    case 'zdSubmit':
      {
        ElMessageBox.confirm(`是否提交制单?`, t('common.delWarning'), {
          confirmButtonText: t('common.delOk'),
          cancelButtonText: t('common.delCancel'),
          type: 'warning'
        }).then(async () => {
          const res = await deliverSetStatus({
            ids: row.id,
            status: 3
          })
          if (res) {
            ElMessage.success('提交成功')
            emitter.emit('getList', 'edit')
          }
        })
      }
      break
    case 'detail':
      {
        // dialogTitle.value = '详情'
        // dialogVisible.value = true
        // tableObject.currentRow = row
        push(`/logistics/invoiceEdit?id=${row.id}&isDetail=true`)
      }
      break
    case 'export':
      {
        let res = await deliverExport(row.id)
        console.log('---出库单导出-res---', res)
        const href = URL.createObjectURL(res.data)
        const box = document.createElement('a')
        box.download = `出库单-运单号${row.waybill}.xls`
        box.href = href
        box.click()
      }
      break
    default:
      break
  }
}
//货物位置
const locationOfGoodsArr: any = reactive([])
const getStoreSelect = async () => {
  let res: any = await storeSelect({})
  res.data.list.forEach((item) => {
    item.type == 1 &&
      locationOfGoodsArr.push({
        label: item.name,
        value: item.id
      })
  })
}
getStoreSelect()
const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as TableData
      const res = await sendEdit(data, data.id)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
    }
  })
}

// 导出出库单
const fhdExport = async (rlues) => {
  if (checkRlues(rlues)) {
    let res = await fhdExportExcel(null)
    console.log('---导出出库单---', res)
    const date = new Date()
    var Y = date.getFullYear()
    var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    const href = URL.createObjectURL(res.data)
    const box = document.createElement('a')
    box.download = `${Y}-${M}-${D}出库单.xls`
    box.href = href
    box.click()
  }
}
</script>

<template>
  <ContentWrap>
    <Search
      :model="{}"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="fhdExport('24-1')">导出出库单</ElButton>
      <!-- <ElButton type="primary" @click="AddAction('24-1')">{{ t('exampleDemo.add') }}</ElButton> -->
      <ElButton :loading="delLoading" type="danger" @click="delData(null, true)">
        {{ t('exampleDemo.del') }}
      </ElButton>
      <ElButton type="warning" @click="cos">{{ t('common.coSourcing') }}</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.limit"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElPopover placement="right" :width="80" trigger="click">
          <template #reference>
            <ElButton type="primary"> ··· </ElButton>
          </template>
          <div class="btnContent">
            <ElButton type="primary" v-if="row.status == 0" @click="action(row, 'ckSubmit', '22-6')"
              >提交配货</ElButton
            >
            <ElButton
              type="primary"
              v-if="row.status == 2 || row.status == 1"
              @click="action(row, 'zdSubmit', '22-6')"
            >
              提交制单
            </ElButton>
            <ElButton type="warning" v-if="row.status == 3" @click="action(row, 'Passed', '24-5')">
              {{ t('purchaseOrder.passedReview') }}
            </ElButton>
            <ElButton type="primary" @click="action(row, 'Edit', '24-2')">
              {{ t('exampleDemo.edit') }}
            </ElButton>
            <ElButton type="success" @click="action(row, 'detail', '24-4')">
              {{ t('router.watch') }}
            </ElButton>
            <!-- <ElButton type="success" @click="action(row, 'export', '24-4')"> 导出 </ElButton> -->
            <ElButton type="danger" @click="delData(row, false, '24-3')">
              {{ t('exampleDemo.del') }}
            </ElButton></div
          >
        </ElPopover>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Detail :detail-schema="allSchemas.detailSchema" :current-row="tableObject.currentRow" />
  </Dialog>

  <ElDialog title="填写合包单号" v-model="tkShow">
    <div class="tkTable">
      <ElSelect v-model="store_id" default style="margin: 20px 0px" placeholder="请选择仓库">
        <ElOption
          v-for="item in locationOfGoodsArr"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </ElSelect>
      <ElInput v-model="ydString" placeholder="请输入运单号,例如:xxx,xxx" />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="tkShow = false">取消</ElButton>
        <ElButton type="primary" @click="confirmTk"> 确认 </ElButton>
      </span>
    </template>
  </ElDialog>
</template>
<style lang="less" scoped>
.btnContent {
  display: flex;
  flex-direction: column;
  :deep .el-button + .el-button {
    margin-left: 0;
    margin-top: 15px;
  }
}
</style>
